## SVT Play doesn't have an open API so let's parse their HTML
require 'date'
require 'time'

module Shin
  module Play
    class Svtplay

      def new
        self
      end

      # Get a show
      def show(params={})
        # Response
        response = Base.get('http://www.svtplay.se/' + params[:slug].to_s + '?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil

        # Can't be nil
        if @main_noko != nil
          # Title
          @image = URI(@main_noko.css('img.play_title-page-trailer__image')[0]['src'].strip) rescue nil
          @image.scheme = 'http' if !@image.nil?

          # Data
          @array = {title: @main_noko.css('header.play_title-page-info__header > h1.play_title-page-info__header-title').text.strip, description: @main_noko.css('p.play_title-page-info__description').last.text.strip, image: @image.to_s, genres: [], episodes: []}

          # Genres
          @main_noko.css('header.play_title-page-info__header > ul.play_tag-list > li').map do |e|
            @array[:genres] << e.text.strip
          end

          # Episodes
          @main_noko.css('div#play_js-tabpanel-more-episodes > ul > li').map do |e|
            @video_id = e.css('a.play_vertical-list__video-element-thumbnail')[0]['href'][/\/video\/(\d+)\//, 1].to_i rescue nil
            @url = "http://www.svtplay.se" + e.css('h2.play_vertical-list__header a')[0]['href'] rescue nil
            @desc = e.css('p.play_vertical-list__description-text').text.strip rescue nil
            @season = e.css('h2.play_vertical-list__header > a').text.strip[/S.song\s+(\d+)/, 1].to_i rescue nil
            @episode = e.css('h2.play_vertical-list__header > a').text.strip[/Avsnitt\s+(\d+)/, 1].to_i rescue nil

            # Try to match in description
            if @episode == 0 or @episode == nil or @episode == ""
              @episode = @desc.strip[/^Del\s+(\d+)/, 1] rescue nil

              # If that doesn't work try url
              if @episode == 0 or @episode == nil or @episode == ""
                @episode = @url.strip[/avsnitt-(\d+)/, 1] rescue nil
              end
            end

            @image = URI(e.css('img.play_vertical-list__image')[0]['src'].gsub("ALTERNATES/small", "ALTERNATES/extralarge")) rescue nil
            @image.scheme = 'http' if !@image.nil?

            @array[:episodes] << {id: @video_id, image: @image.to_s, season: @season, episode: @episode, subtitle: @subtitle, url: @url, description: @desc}
          end
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end

        @array.to_hashugar
      end

      # Get episodes for a slug
      def episodes(params={})
        # Response
        response = Base.get('http://www.svtplay.se/' + params[:slug].to_s + '/hela-program?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil

        # Can't be nil
        if @main_noko != nil
          # Title
          @title = @main_noko.css('div.play_gridpage__header-wrapper > h1 > a.play_link.play_link--discreet').text.strip rescue nil
          @next_page = @main_noko.css('div.play_gridpage__pagination').css('a')[0]['href'][/\?sida\=(\d+)/, 1].to_i rescue nil

          # Data
          @array = {next_page: @next_page, results: []}

          # Multiple episodes
          @main_noko.css('div#gridpage-content > article').map do |e|
            @video_id = e.css('a')[0]['href'][/\/video\/(\d+)\//, 1].to_i rescue nil
            @url = "http://www.svtplay.se" + e.css('a')[0]['href'] rescue nil
            @desc = e.css('a')[0]['title'] rescue nil
            @season = e['data-season'].to_i rescue nil
            @episode = e['data-title'][/Avsnitt\s+(\d+)/, 1].to_i rescue nil
            @image = URI(e.css('a img')[0]['src'].gsub("ALTERNATES/small", "ALTERNATES/extralarge")) rescue nil
            @image.scheme = 'http' if !@image.nil?

            # Parse published_to
            if pto = e['data-available']
              # Days
              if dayz = pto[/(\d+)\s+dag/, 1].to_i
                @published_to = Time.parse("23:59", Date.today + dayz) rescue nil
              else
                @published_to = nil
              end
            end


            # subtitle
            if @episode > 0
              @subtitle = e['data-title'].gsub(@title + " - ", '').gsub("Avsnitt " + @episode.to_s + ':', '').gsub("Avsnitt " + @episode.to_s, '').strip
            else
              @subtitle = e['data-title'].gsub(@title + " - ", '').strip
            end

            # Try to match in description
            if @episode == 0 or @episode == nil or @episode == ""
              @episode = @desc.strip[/^Del\s+(\d+)/, 1] rescue nil

              # If that doesn't work try url
              if @episode == 0 or @episode == nil or @episode == ""
                @episode = @url.strip[/avsnitt-(\d+)/, 1] rescue nil
              end
            end

            @array[:results] << {id: @video_id, image: @image.to_s, season: @season, episode: @episode, subtitle: @subtitle, url: @url, description: @desc, published_to: @published_to}
          end
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end

        @array.to_hashugar
      end

      # Programs
      def programs
        # Response
        response = Base.get('http://www.svtplay.se/program')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil

        # Foreach programs
        @array = []

        # Cant be nil
        if @main_noko != nil
          @main_noko.css('ul.play_alphabetic-list > li > ul > li').map do |p|
            sluge = p.css('a')[0]['href'].strip.gsub("/", '')
            titlee = p.css('a').text
            @array << {slug: sluge, title: titlee}
          end

        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end

        @array.to_hashugar
      end

      # Video
      def video(params={})
        # Response
        response = Base.get('http://www.svtplay.se/video/' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil

        # Cant be nil
        if @main_noko != nil
          # Title
          @title = @main_noko.css("a.play_video-area-aside__linked-title")[0].text.strip

          # Subtitle data
          submeta = @main_noko.css("h2.play_video-area-aside__sub-title")[0].text.strip.gsub("\n", ' ').squeeze(' ') rescue nil
          if !submeta.nil?
            @season = submeta[/S.song\s+(\d+)/, 1].to_i rescue nil
            @episode = submeta[/Avsnitt\s+(\d+)/, 1].to_i rescue nil
          end

          # Desc
          @desc = @main_noko.css('p.play_video-area-aside__info-text')[0].text.strip rescue nil

          # Genres
          @genres = []
          @main_noko.css('div.play_video-area-aside__info > ul.play_tag-list > li').map do |e|
            @genres << e.text.strip
          end

          # Player data
          playerdata = @main_noko.css("a.play_js-svtplayer")[0]
          @published_on = Time.at(playerdata['data-popularity-publish-date'].to_i/1000) rescue nil
          pub_to = @main_noko.css('p.play_video-area-aside__info-text').last.text.strip rescue nil

          if !pub_to.nil? and dayz = pub_to[/(\d+) dag/, 1].to_i
            @published_to = Time.parse("23:59", (Date.today + dayz).to_time) rescue nil
          else
            @published_to = nil
          end
          @url = playerdata['data-popularity-url'] rescue nil
          @length = (playerdata['data-length'].to_i)/60 rescue nil
          @image = URI(@main_noko.css('meta[property="og:image"]')[0]['content'].gsub("ALTERNATES/medium", "ALTERNATES/extralarge")) rescue nil
          @image.scheme = 'http' if !@image.nil?

          # Add subtitle from playerdata
          if submeta != nil and @episode > 0
            @subtitle = playerdata['data-title'].gsub(@title + " - ", '').gsub("Avsnitt " + @episode.to_s + ':', '').gsub("Avsnitt " + @episode.to_s, '').strip

            @subtitle = nil if @subtitle == ""
          else
            @subtitle = playerdata['data-title'].gsub(@title + " - ", '').strip
            @subtitle = nil if @subtitle == ""
          end

          # Try to match in description
          if @episode == 0 or @episode == nil or @episode == ""
            @episode = @desc.strip[/^Del\s+(\d+)/, 1] rescue nil

            # If that doesn't work try url
            if @episode == 0 or @episode == nil or @episode == ""
              @episode = @url.strip[/avsnitt-(\d+)/, 1] rescue nil
            end
          end

          { id: params[:id].to_i, title: @title, image: @image.to_s, season: @season, episode: @episode, subtitle: @subtitle, length: @length, published_on: @published_on, published_to: @published_to, url: @url, description: @desc, genres: @genres }.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end
      end


      # Errors
      class NotValid         < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end
